<?php


namespace App\Service\Admin;


use App\Constants\ErrorCode;
use App\Constants\Model\User;
use App\Dao\UserDao;
use App\Exception\BusinessException;
use Hyperf\Di\Annotation\Inject;

class UserService extends BaseService
{

    /**
     * @Inject()
     * @var UserDao
     */
    protected $userDao;

    /**
     * @param array $where
     * @return array
     */
    public function index(array $where): array
    {
        $pageInfo = $this->extractPaginateInfo($where);
        $users = $this->userDao->where($where)->paginate(
            $pageInfo['perPage'],['*'],'page',$pageInfo['page']
        );
        return $this->formatIndex($users);
    }

    public function formatIndex(\Hyperf\Contract\LengthAwarePaginatorInterface $index)
    {
        $data = [];
        /** @var \App\Model\User $user */
        foreach ($index->items() as $user) {
            $data[] = [
                'id' => $user->id,
                'nickname' => $user->nickname,
                'avatar' => $user->avatar,
                'personal_certification' => $user->personal_certification,
                'phone' => $user->phone,
                'done_task_exec_count' => $user->done_task_exec_count,
                'commission' => $user->commission,
                'withdraw_amount' => $user->withdrawAmount,
                'credit_point' => $user->credit_point,
                'level' => $user->level,
                'cooperative_name' => $user->cooperative->nickname,
                'created_at' => $user->created_at->toDatetimeString()
            ];
        }

        return [
            'data' => $data,
            'current_page' => $index->currentPage(),
            'total' => $index->total(),
            'per_page' => $index->perPage()
        ];
    }

    public function block(int $id)
    {
        $user = $this->userDao->first(['id' => $id]);
        // TODO 这里要写操作日志

        if (User::STATUS_BLOCKED == $user->status) {
            throw new BusinessException(ErrorCode::USER_HAS_BEEN_BLOCKED);
        }
        $user->status = User::STATUS_BLOCKED;
        return $user->save();
    }

    public function unblock(int $id)
    {
        $user = $this->userDao->first(['id' => $id]);
        // TODO 这里要写操作日志

        if (User::STATUS_UNBLOCK == $user->status) {
            throw new BusinessException(ErrorCode::USER_HAS_BEEN_UNBLOCKED);
        }
        $user->status = User::STATUS_UNBLOCK;
        return $user->save();
    }

}